<?php
namespace control;
// 固定资产登记
class assetListClass extends adIndexClass
{
	private const page  = 'assetList'; # 权限
	private const table = 'asset';     # 数据表
	private const title = '固定资产';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'changeRecord':
                $tr = [
                    'type'          => [
                        'name'  => "变动类型",
                        'width' => 300,
                        'sort' => 1,
                    ],
                    'userDepartment'  => [
                        'name'  => '使用人部门',
                        'width' => 300,
                    ],
                    'user'         => [
                        'name'  => '使用人',
                        'width' => 300,
                    ],
                    'storage'          => [
                        'name'  => '存放地点',
                        'width' => 300,
                    ],
                    'time'          => [
                        'name'  => '变动时间',
                        'width' => 300,
                        'sort' => 1,
                    ]
                ];
                break;
            default:
                $tr = [
                    'orderNo'          => [
                        'name'  => "卡片编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'name'  => [
                        'name'  => '名称',
                        'width' => 150,
                    ],
                    'brand'         => [
                        'name'  => '品牌',
                        'width' => 150,
                    ],
                    'model'          => [
                        'name'  => '规格型号',
                        'width' => 150,
                    ],
                    'unit'          => [
                        'name'  => '计量单位',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ],
                    'departmentId'          => [
                        'name'  => '使用部门',
                        'width' => 150,
                    ],
                    'user'          => [
                        'name'  => '使用人',
                        'width' => 100,
                    ],
                    'discountYear'          => [
                        'name'  => '折旧年限（月）',
                        'width' => 120,
                    ],
                    'purchaseMoney'          => [
                        'name'  => '资产原值('.static::$unit.')',
                        'width' => 120,
                    ],
                    'monthNum'          => [
                        'name'  => '已计提月数',
                        'width' => 120,
                    ],
                    'monthDecMoney'          => [
                        'name'  => '月折旧额('.static::$unit.')',
                        'width' => 120,
                    ]
                ];
        }
        return $tr;
    }

	/*固定资产入口页*/
	public function home()
	{
		$option['click'] = 'replaceContent(this, \'assetList\')';
		$all             = assetCatalogClass::getCatalogAll($option);
		//返回
		$rightHtml = $this->homeRight();
		$html = componentClass::leftNav([
            'title'=>'搜索分类',
            'click'=>$option['click'],
            'allTitle'=>'全部分类',
            'all'=>$all,
            'rightHtml'=>$rightHtml,
        ]);
		//返回
		return $this->homeFun($html);
	}

	/**
	 * 左侧搜索框
	 *
	 * @return string
	 */
	public function getContainerLeftJson(): string
	{
		$option['click'] = 'replaceRight(this, \'assetList\')';
		$json['html']    = assetCatalogClass::getCatalogAll($option);
		return json_encode($json, 320);
	}

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编码" => text(array("name" => "orderNo")).
                        hidden(['name' => 'objId', 'value' => $this->post('objId')]),
                    "固定资产编码"   => text(array("name" => "orderNo")),
                    "名称"   => text(array("name" => "name")),
                ],
                [
                    "品牌"   => text(array("name" => "brand")),
                    "规格型号"   => text(array("name" => "model")),
                    "状态" => select(["name" => "state", 'option' => ['在库', '维护中', '使用中']]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

	public function homeRight()
	{
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .= "<a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData' class='spanButton'>导出</a>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= '<a href="javascript:;" onclick="printPage(\'' . $this->get('cla') . '\')" class="spanButton">打印</a>';
        }
		//返回
		return $this->search($html, layout: 'pop', toolButton: $button);
	}

	/**
	 * 异步加载
	 *
	 */
	public function homeRightJson()
	{
		$json['html'] = $this->homeRight();
		return json_encode($json, 320);
	}

	public function homeRightJsonSearch()
	{
		return $this->homeSearch();
	}

	/*固定资产列表*/
	public function homeSearch()
	{
		//全等查询数组
		$equal = [
			'state' => $this->post('state'),
			'acid'  => $this->post('objId'),
            'coid'=>self::$coid
		];
		$like  = [
			'orderNo' => $this->post('orderNo'),
			'name'    => $this->post('name'),
			'brand'   => $this->post('brand'),
			'model'   => $this->post('model'),
		];
		//生成查询语句
		$where                         = search([
			"="    => $equal,
			"like" => $like,
		]);
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
		$page                          = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
		//获取记录
		foreach ($page['array'] as $array) {
			//列表控件
			$dominate = array(
				"box"    => ["name" => "listId", "value" => $array['id']],
				"detail" => [
					"title" => "固定资产详情",
					"click" => "newIframe('固定资产详情','" . root . "control/adIndex.html?cla=assetList&fun=detail&id=" . $array['id'] . "')",
				],
			);
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case 'departmentId':
                        $row[] = departmentClass::getTypeName($array['departmentId']);
                        break;
                    case 'user':
                        $row[] = self::findStaff($array['user']);
                        break;
                    case 'monthNum':
                        $monthNum  = find(array('table'=>'asset_depreciation as a join asset_depreciation_detail as b on a.id = b.orderId','field'=>"ifnull(count(a.id),0) as total",'single'=>"a.state = '已通过' and a.coid = '".self::$coid."' and b.atid = '$array[id]'"))['total'];
                        $row[] = $monthNum;
                        break;
                    case 'monthDecMoney':
                        $endDate = date('Y-m').'-'.sprintf('%02d',date('t'));
                        $ratio = assetManagementClass::monthRatio($array['depreciationMethod'],$array['discountYear'],$array['money'],$array['purchaseMoney'],$array['depreciationMoney'],$array['purchaseDate'],$endDate,1);
                        $monthDecMoney =assetManagementClass::monthDecMoney($array['depreciationMethod'],$array['purchaseMoney'],$ratio/100,$array['purchaseDate'],$endDate,$array['discountYear'],$array['money'],$array['depreciationMoney']);
                        $row[] = $monthDecMoney;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
        $total = find([
            'table'  => self::table,
            'single' => $where,
            'field'  => "ifnull(sum(num),0) as num,ifnull(sum(purchaseMoney),0) as purchaseMoney",
        ]);
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
		//返回
		$json['html'] = $page['hint'] . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
		return json_encode($json, 320);
	}


	public function printPage()
	{
		$array = $this->get('body') ? explode(';', $this->get('body')) : [];
		if (empty($array)) {
			$tpl = '<h1>参数不能为空</h1>';
		} else {
			$tpl    = '';
			$result = self::filterNull($array);
			foreach ($result as $id) {
				$info = query('asset', " id = '$id' ");
				$url = urlencode($this->root.self::page.'?url='.$info['orderNo']);
				$tpl  .= <<<EOT
                <div class="asset-qr-box" style="margin:10px 0">
                    <div class="asset-qr-img left">
                        <img src="{$this->root}/pay/wxpay/wxScanPng.php?url={$url}" width="150">
                    </div>
                    <div class="asset-qr-ul left">
                        <p>编码：{$info['orderNo']}</p>
                        <p>名称：{$info['name']}</p>
                        <p>开始使用日期：{$info['purchaseDate']}</p>
                    </div>
                </div>
EOT;
			}
		}
		$html = <<<EOT
        <div id="content-box" style="display: none">
            <div data-op-type='new-page'></div>
            {$tpl}
        </div>
EOT;
		return (new printClass())->showPrint($html);
	}

	/**
	 * 详情页
	 *
	 * @return string
	 */
	public function detail(): string
	{
		$info = query(self::table, " id = '" . $this->get('id') . "' ");
		if (!$this->power(self::page, "see")) {
			$html = "你没有查看权限";
		} elseif (!$this->get('id')) {
			$html = "ID为空";
		} elseif (!$info['id']) {
			$html = "未找到此信息";
		} else {
			$data = [
				"id"   => $info['id'],
				"menu" => [
					"detail"       => "基本信息",
					"changeRecord" => "变动记录",
				],
			];
			//按钮
			$button = [];
			// 二维码
            $yumuCorpId = para('yumuCorpId');
            $url = urlencode($this->root.self::page.'?url='.$info['orderNo'].'&pass&'.$yumuCorpId);
			$qrUrl  = $this->root . 'pay/wxpay/wxScanPng.php?url=' .$url;
			$qrHtml = '<div class="asset-qr-box">
                            <div class="asset-qr-img left">
                                <img src="' . $qrUrl . '" width="150">
                            </div>
                            <div class="asset-qr-ul left">
                                <p>编码：' . $info['orderNo'] . '</p>
                                <p>名称：' . $info['name'] . '</p>
                                <p>开始使用日期：' . $info['purchaseDate'] . '</p>
                            </div>
                            </div>
                        </div>';
			//生成表单
			$data['html'] = $this->tableShow([
				"button" => $button,
				"基本信息"   => [
					[
						"分类" => assetCatalogClass::getCatalogName($info['acid']),
						"名称" => $info['name'],
						"品牌" => $info['brand'],
                        "规格型号" => $info['model'],
					],
                    [
                        "单位" => $info['unit'],
                        "数量" => $info['num'],
                        "附件清单" => $info['fileList'],
                        "开始使用日期" => $info['purchaseDate'],
                    ],
                    [
                        "资产原值(". static::$unit . ")" => self::formateNumber($info['purchaseMoney']),
                        "预计净残值(". static::$unit . ")" => self::formateNumber($info['money']),
                        "累计折旧(". static::$unit . ")" => self::formateNumber($info['depreciationMoney']),
                        "折价期限(月)" => $info['discountYear'],
                    ],
                    [
                        "折旧方式" => $info['depreciationMethod'],
                        "闲置资产" => $info['unused'],
                        "使用部门" => departmentClass::getTypeName($info['departmentId']),
                        "使用人" => self::findStaff($info['user']),
                    ],
                    [
                        "存放地点" => $info['storage'],
                    ],
                    [
                        "备注" => pre($info['text']),
                    ],
				],
				"系统信息"   => [
					[
						"卡片编码" => $info['orderNo'],
						"登记人"    => self::findStaff($info['stid']),
						"登记时间"   => self::formatDate($info['time']),
                        "更新时间" => self::null($info['updateTime']),
					],
					[
						"状态"   => $info['state'],
					],
				],
				"条码"     => [
					[
						$qrHtml,
					],
				],
			]);
			//生成页面
			$html = $this->tab($data);
		}
		//返回
		return $html;
	}

	/**
	 * 变动记录
	 *
	 */
	public function changeRecord()
	{
		$where = " atid = '{$this->get('id')}' ";
        //排序
        $orderBy = $this->listSort(array(
            "search" => $this->post('list_sort_key') ?: 'time',
            "sort"   => $this->post('list_sort') ?: "desc",
            "array"  => array(),
        ));
		$page  = $this->page(["table" => "asset_revert", "where" => $where, "order" => $orderBy['orderBy']]);
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
		//获取记录
		foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "user":
                        $row[] = self::findStaff($array['user']);
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
		}
		//控件
		$button = "";
        //生成页面
        $li = $this->li(array(
            "body"        => $body,
            "install"     => $installSearch,
            "button"      => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page"        => $page['para'],
        ));
		//返回
		$json['html'] = "<div class='p-l-r-15'>" . $page['hint'] . $button . "<form name='workOutForm'>" . space . $li . "</form>" . $page['button'] . clear . "</div>";
		return json_encode($json, 320);
	}

	/**
	 * 导出
	 */
	public function exportData()
	{
		if (!$this->power(self::page, 'export')) {
			$_SESSION['warn'] = '你还没有导出的权限';
		} else {
			$data   = [];
			$sql  = $_SESSION[self::page]['sql'];
			$title  = ['卡片编码', '名称', '品牌', '规格型号','数量','单位','附件清单', '开始使用日期','状态', '使用部门', '使用人', '存放地点', '资产原值('.static::$unit.')', '预计净残值('.static::$unit.')', '累计折旧('.static::$unit.')', '折价期限(月)', '折旧方式', '闲置资产', '备注'];
			$result = self::sqlFind($sql);
			if (is_array($result)) {
				foreach ($result as $array) {
					//本列
					$data[] = [
						$array['orderNo'],
						$array['name'],
						$array['brand'],
						$array['model'],
                        $array['num'],
                        $array['unit'],
                        $array['fileList'],
                        $array['purchaseDate'],
						$array['state'],
                        departmentClass::getTypeName($array['departmentId']),
						self::findStaff($array['user']),
						$array['storage'],
						$array['purchaseMoney'],
						$array['money'],
                        $array['depreciationMoney'],
                        $array['discountYear'],
                        $array['depreciationMethod'],
                        $array['unused'],
                        $array['text'],
					];
				}
			}
			$text = $this->control['name'] . "导出了" . self::title;
			$this->logText(["type" => self::page, "text" => $text]);
			$this->excelOut($title, $data, self::title . ".xlsx");
		}
		header("Location:" . getenv("HTTP_REFERER"));
		exit(0);
	}
}
